<template>
  <!-- 此子组件适用于及时上传文件，非及时上传需另做扩展 -->
  <form :id="uploadForm">
    <input type="file" :id="clickUpload" name="file" @change="fileChange" />
  </form>
</template>
<script>
import jqFrom from '../../kits/jquery.form'
import common from '../../kits/common'

export default {
  data() {
    return {}
  },
  //搜索条件
  props: {
    uploadForm: {
      type: String,
    },
    clickUpload: {
      type: String,
    },
    uploadUrl: {
      type: String,
    },
    upLoadFile: {
      type: Array,
    },
  },
  mounted() {},
  computed: {},
  methods: {
    fileChange() {
      var Filedata
      var file
      var fileSize
      Filedata = $('#' + this.clickUpload).val()
      if (!Filedata) {
        return
      }
      try {
        file = $('#' + this.clickUpload)[0].files[0]
        fileSize = (file.size / 1024).toFixed(0)
      } catch (e) {
        this.$message({
          message:
            '您的浏览器暂不支持计算上传文件的大小，确保上传文件不要超过2M，建议使用FireFox、Chrome或IE10以上浏览器。',
          type: 'warning',
        })
      }
      // 文件大小和限制类型可以通过子组件传值区分，若不适应于使用页面，可自行判断
      if (this.upLoadFile.length == 5) {
        this.$message({
          message: '最多上传5个附件',
          type: 'warning',
        })
        $('#' + this.clickUpload).val('')
        return
      }
      if (fileSize / 1 > 1024 * 2) {
        this.$message({
          // message: "最多能上传2M以内的图片",
          message: '要求格式为JPG、PNG格式，图片大小不超过2M',
          type: 'warning',
        })
        $('#' + this.clickUpload).val('')
        return
      }
      if (!/\.(png|jpg|jpeg|PNG|JPG|JPEG)$/.test(Filedata)) {
        this.$message({
          // message: "仅支持上传png、jpg、jpeg格式文件",
          message: '要求格式为JPG、PNG格式，图片大小不超过2M',
          type: 'warning',
        })
        $('#' + this.clickUpload).val('')
        return
      }
      let that = this
      var options = {
        url: common.uploadUrl + that.uploadUrl,
        type: 'POST',
        dataType: 'json',
        success: function (data) {
          that.$emit('getUpLoadFileData', data, that.uploadForm)
          that.$emit('getSrcListData', data, that.uploadForm)
          that.$emit('getOldSrcListData', data, that.uploadForm)
          $('#' + that.clickUpload).val('')
        },
        error: function () {},
      }
      $('#' + that.uploadForm).ajaxSubmit(options)
      return false
    },
  },
}
</script>
<style scoped lang="less"></style>
